package service

import (
	"errors"
)

type DetailRequest struct {
	ID uint `json:"id,omitempty" binding:"required,min=1"`
}
type Detail struct {
	ID            uint   `json:"id,omitempty"`
	Title         string `json:"title,omitempty"`
	ImageUrl      string `json:"image_url,omitempty"`
	Desc          string `json:"desc,omitempty"`
	Public        bool   `json:"public,omitempty"`
	UserID        uint   `json:"user_id,omitempty"`
	Username      string `json:"username,omitempty"`
	Nickname      string `json:"nickname,omitempty"`
	LikeCount     int    `json:"like_count"`
	CommentCount  int    `json:"comment_count"`
	FavoriteCount int    `json:"favorite_count"`
	LikeState     bool   `json:"like_state"`
}

func (svc *Service) GetDetail(params *DetailRequest) (*Detail, error) {
	_, exist := svc.ctx.Get("userID")
	picture, err := svc.dao.GetPicture(params.ID)
	if err != nil {
		return nil, err
	}
	if !exist && !picture.Public {
		return nil, errors.New("登录用户信息不存在")
	}
	user, err := svc.dao.GetUser(picture.UserID)
	if err != nil {
		return nil, err
	}
	likeCount, err := svc.CountLiked(&CountLikeRequest{
		PictureID: picture.ID,
	})
	if err != nil {
		return nil, err
	}
	commentCount, err := svc.CountComments(&CountCommentsRequest{
		PictureID: picture.ID,
	})
	if err != nil {
		return nil, err
	}
	favoriteCount, err := svc.CountFavoritePictureByPID(&CountFavoritePictureByPIDRequest{
		PictureID: picture.ID,
	})
	if err != nil {
		return nil, err
	}
	var likeState bool = false
	if exist {
		like, err := svc.GetLike(&LikeRequest{
			PictureID: picture.ID,
		})
		if err != nil {
			return nil, err
		}
		likeState = like.State
	}

	return &Detail{
		ID:            picture.ID,
		Title:         picture.Title,
		ImageUrl:      picture.ImageUrl,
		Desc:          picture.Desc,
		Public:        picture.Public,
		UserID:        user.ID,
		Username:      user.Username,
		Nickname:      user.Nickname,
		LikeCount:     likeCount,
		CommentCount:  commentCount,
		FavoriteCount: favoriteCount,
		LikeState:     likeState,
	}, nil
}
